package br.com.jm.scwcd.obj3.filters;

import java.io.IOException;
import java.io.StringWriter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet Filter implementation class CopyrightFilter
 */
public class CopyrightFilter implements Filter {

    /**
     * Default constructor. 
     */
    public CopyrightFilter() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		CopyrightResponseWrapper wrapper = new CopyrightResponseWrapper((HttpServletResponse)response);
		chain.doFilter(request, wrapper);
		
		StringWriter stringWriter = wrapper.getInternalBuffer();
		StringBuffer buffer = stringWriter.getBuffer();
		
		final int closingBodyIndex = buffer.indexOf("</body>");
		
		response.getWriter().print(buffer.substring(0, closingBodyIndex));
		
		response.getWriter().println("<p>");
		response.getWriter().println("&copy; Devimedia - All rights reserved");
		response.getWriter().println("</p>");
		response.getWriter().println("</body>");
		response.getWriter().println("</html>");
		response.getWriter().flush();
		
		
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}
